package com.zqh.forum.controller;

import com.zqh.forum.common.AppResult;
import com.zqh.forum.common.ResultCode;
import com.zqh.forum.config.AppConfig;
import com.zqh.forum.exception.ApplicationException;
import com.zqh.forum.model.Article;
import com.zqh.forum.model.Board;
import com.zqh.forum.model.User;
import com.zqh.forum.services.IArticleService;
import com.zqh.forum.services.IBoardService;
import com.zqh.forum.services.impl.ArticleServiceImpl;
import com.zqh.forum.services.impl.UserServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Tag(name = "文章接口")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IBoardService boardService;

    /**
     * 发布新帖
     * @param boardId 板块id
     * @param title   文章标题
     * @param content  帖子内容
     * @return
     */
    @PostMapping("/create")
    @Operation(summary = "发布新帖")
    @Parameters({
            @Parameter(name = "boardId",description = "板块id"),
            @Parameter(name = "title",description = "文章标题"),
            @Parameter(name = "Content",description = "帖子内容")})
    public AppResult create(HttpServletRequest request,
                            @RequestParam("boardId") @NonNull Long boardId,
                            @RequestParam("title") @NonNull String title,
                            @RequestParam("content") @NonNull String content){
        //1.判断用户是否禁言
        //从session中获取登录用户的信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断是否被禁言
        if(user.getState() == 1){
            //用户已经禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2.校验板块的id是否存在
        Board board = boardService.selectById(boardId.longValue());
        //判断查询出来的信息是否是存在的数据id
        if(board == null ||
                board.getDeleteState() == 1 ||
                board.getState() == 1){
            //查询出来的结果不合法
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //3.封装文章对象，后面给session层传递的时候传递的就是对象
        Article article = new Article();
        article.setTitle(title); //标题
        article.setContent(content); //正文
        article.setBoardId(boardId); //板块id
        article.setUserId(user.getId()); //作者id

        //调用session
        articleService.create(article);
        return AppResult.success();
    }

    @GetMapping("/getAllByBoardId")
    @Operation(summary = "获取帖子列表")
    @Parameter(name = "boardId",description = "板块id")
    public AppResult<List<Article>> getAllByBoardId(@RequestParam(value = "boardId",required = false) Long boardId){
        List<Article> articles;
        //1.判断id是否为null
        if(boardId == null){
            //全部信息
            //调用service层查询所有的帖子
             articles = articleService.selectAll();

        }else{
            //输入id查询的信息
             articles = articleService.selectAllByBoardId(boardId);
        }
        if(articles == null){
            articles = new ArrayList<>();
        }
        //返回结果
        return AppResult.success(articles);
    }

    @GetMapping("/getDetails")
    @Operation(summary = "根据帖子id获取帖子详情")
    @Parameter(name = "id",description = "帖子id")
    public AppResult<Article> getDetails(HttpServletRequest request,@RequestParam("id") @NonNull Long id){

        //从session中获取id属性
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service层
        Article article = articleService.selectDetailById(id);
        //判断结果是否为空
        if(article == null){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断访问的用户是否是作者本人
        if(user.getId().equals(article.getUserId())){
            //设置为作者
            article.setOwn(true);
        }
        //返回结果
        return AppResult.success(article);
    }

    @Operation(summary = "编辑帖子")
    @PostMapping("/modify")
    @Parameters({
            @Parameter(name = "id", description = "帖子id"),
            @Parameter(name = "title", description = "帖子标题"),
            @Parameter(name = "content", description = "帖子内容")
    })
    public AppResult modify(HttpServletRequest request,
                            @RequestParam("id") @NonNull Long id,
                            @RequestParam("title") @NonNull String title,
                            @RequestParam("content") @NonNull String content){
        //1.获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //2.校验用户的状态
        if(user.getState() == 1){
            //禁言状态
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3.根据帖子id查询帖子的详情信息
        Article article = articleService.selectById(id);
        //校验帖子是否有效
        if(article == null){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //4.判断用户是不是作者
        if(user.getId() != article.getUserId()){
            //不是作者本人
            //打印日志
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN));
        }
        //5.判断帖子状态是否异常(删除或者禁言)归档
        if(article.getState() == 1 || article.getDeleteState() == 1){
            //返回错误信息
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //6.调用service层
        articleService.modify(id,title,content);
        log.info("帖子更新成功，article id = " + id + "user id = " + user.getId());

        return AppResult.success();
    }

    @Operation(summary = "点赞帖子")
    @PostMapping("/thumbsUp")
    @Parameter(name = "id" ,description = "帖子id")
    public AppResult thumbsUp(HttpServletRequest request,@RequestParam("id") @NonNull Long id){
        //校验用户的状态是否为禁言，禁言的状态就不可以操作信息
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            //禁言
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        Article article = articleService.selectById(id);
        if(article == null || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //调用service层
        articleService.thumbsUpById(id);
        //返回结果
        return AppResult.success();
    }

    @Operation(summary = "删除帖子")
    @PostMapping("/deleteById")
    @Parameter(name = "id", description = "帖子id")
    public AppResult deleteById(HttpServletRequest request, @RequestParam("id") @NonNull Long id){
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);

        if(user.getState() == 1){
            //禁言
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        if(article == null || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //校验当前访问的人是不是作者本人
        if(user.getId() != article.getUserId()){
            //不是作者
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用session
        articleService.deleteById(id);
        //返回结果
        return AppResult.success();
    }

    @Operation(summary = "根据用户id查询帖子列表")
    @GetMapping("/getAllByUserId")
    @Parameter(name = "userId",description = "用户id")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,@RequestParam(value = "userId",required = false) Long userId){
        List<Article> articles = null;
        if(userId == null){
            //1.查询登录用户的信息
            //查询登录用户id
            HttpSession session = request.getSession(false);
            User user = (User)session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //2.查询指定用户的信息
         articles = articleService.selectByUserId(userId);
        //返回结果
        return AppResult.success(articles);
    }



}
